"""
分布式锁数据模型
用于在Kubernetes集群中实现分布式锁
"""
from sqlalchemy import Column, String, DateTime, Text, Index
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from app.database.base import Base
import uuid


class DistributedLock(Base):
    """分布式锁表"""
    __tablename__ = "distributed_locks"
    
    # 基础字段
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    lock_key = Column(String(200), unique=True, nullable=False, comment="锁的唯一标识")
    lock_token = Column(String(100), nullable=False, comment="锁令牌")
    node_id = Column(String(100), nullable=False, comment="持有锁的节点ID")
    
    # 时间字段
    expire_time = Column(DateTime(timezone=True), nullable=False, comment="锁过期时间")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    
    # 可选字段
    description = Column(Text, comment="锁描述信息")
    
    # 索引优化
    __table_args__ = (
        Index('idx_distributed_locks_key', 'lock_key'),
        Index('idx_distributed_locks_expire', 'expire_time'),
        Index('idx_distributed_locks_node', 'node_id'),
        {"comment": "分布式锁表"}
    )